package com.chaos.framework.model.serivce;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Builder
public class RedisLockedFunction<T, R> {
    private final RedissonDistributedLock redisBean;
    private final String redisKey;
    private final long lockSeconds;
    private final boolean showInfoLog;

    private final Function<T, R> function;

    public R apply(T t, R defaultValue) {
        Objects.requireNonNull(redisBean, "redisBean 不能为空");
        Objects.requireNonNull(redisKey, "redisKey 不能为空");
        Objects.requireNonNull(function, "function 不能为空");

        boolean tryLock = redisBean.tryLock(redisKey, lockSeconds, TimeUnit.SECONDS);
        try {
            if (tryLock) {
                if (showInfoLog) {
                    log.info("获取redis锁成功, key: {}", redisKey);
                }
                return function.apply(t);
            }

            return defaultValue;
        } finally {
            if (tryLock) {
                redisBean.unlock(redisKey);
                if (showInfoLog) {
                    log.info("释放redis锁成功, key: {}", redisKey);
                }
            }
        }
    }
}
